package com.youdianstar.app.support.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.youdianstar.app.api.ApiService
import com.youdianstar.app.entity.PromoRecord
import com.youdianstar.app.common.PAGE_SIZE
import com.youdianstar.app.common.event.NetEventLiveData
import com.youdianstar.app.common.util.LogUtil
import java.io.IOException


/**
 * File: PromoPagingSource
 * Author: 82149 Create: 2022/03/03
 * Changes (from 2022/03/02)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class PromoPagingSource(
    private val service: ApiService,
    private val eventLiveData: NetEventLiveData? = null
) : PagingSource<Int, PromoRecord>() {

    override fun getRefreshKey(state: PagingState<Int,PromoRecord>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int,PromoRecord> {
        //分页请求是按 offset/偏移量 决定的,所以key值内容不是页码Page,是当前数据下标index
        val index = params.key ?: 0 //当前数据下标,从0开始
        try {
            val data = service.getPromoRecords(index)
            val dataSize: Int = if (null == data.data) 0 else data.data!!.size
            val preKey = if (index > 0) index - PAGE_SIZE else null
            LogUtil.d("----load index = " + index + ";-Size = " + dataSize)
            if (index == 0 && dataSize == 0) {
                eventLiveData?.postValue(NetEventLiveData.Result.RESULT_EMPTY)
            } else {
                eventLiveData?.postValue(NetEventLiveData.Result.RESULT_OK)
            }
            return LoadResult.Page(
                //当前页加载的数据
                data.data!!,
                // 往上加载的Key ,如果不可以往上加载就null
                prevKey = null,
                // 加载下一页的key 如果传null就说明到底了
                nextKey = (if (dataSize < PAGE_SIZE) null else dataSize + index)
            )
        } catch (e: IOException) {
            e.printStackTrace()
            if (index == 0)
                eventLiveData?.postValue(NetEventLiveData.Result.RESULT_ERROR)
            return LoadResult.Error(e)
        } catch (e: Exception) {
            e.printStackTrace()
            eventLiveData?.postValue(NetEventLiveData.Result.NET_ERROR)
            return LoadResult.Error(e)
        }
    }

}